package com.example.lenovo.asia5b.my.myWallet.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.example.lenovo.asia5b.commodity.activity.ServiceActivity;
import com.example.lenovo.asia5b.my.activity.CreditCardUrlActivity;
import com.example.lenovo.asia5b.my.bean.FPXBean;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.util.DensityUtil;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.Setting;
import com.example.lenovo.asia5b.util.StringUtil;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.BaseFragment;
import fay.frame.ui.U;

import static com.example.lenovo.asia5b.util.SharedPreferencesUtils.getUserBean;


/**
 * 我的钱包
 * Created by lenovo on 2017/6/22.
 */

public class FPXFragment extends BaseFragment  implements ICallBack {
    public View fragmentView;
    private TextView txt_500,txt_200,txt_100,txt_60;
    private TextView txt_money;
    private Button btn_top_up;
    private List<TextView> RMTexts ;
    private EditText edit_other_amount,edit_email;
    private String amount;
    private LoadingDalog loadingDalog;
    private LinearLayout ll_xy;
    private CheckBox chb_protocol;
    private String  pay_id;
    private Spinner spr_bank;
    private LinearLayout ll_fpx;

    private List<FPXBean> listBanks ;
    private List<String> listBankId;
    private String bank_id;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        fragmentView = inflater.inflate(R.layout.frame_fpx, container,
                false);

        initView();
        fpxbankListData();
        return fragmentView;
    }

    public void initView() {
        loadingDalog = new LoadingDalog(getActivity());
        ll_fpx = (LinearLayout)fragmentView.findViewById(R.id.ll_fpx);
        ll_fpx.setVisibility(View.VISIBLE);
        txt_500 = (TextView)fragmentView.findViewById(R.id.txt_500);
        txt_200 = (TextView)fragmentView.findViewById(R.id.txt_200);
        txt_100 = (TextView)fragmentView.findViewById(R.id.txt_100);
        txt_60 = (TextView)fragmentView.findViewById(R.id.txt_60);
        btn_top_up = (Button)fragmentView.findViewById(R.id.btn_top_up);
        spr_bank = (Spinner)fragmentView.findViewById(R.id.spr_bank);
        edit_other_amount = (EditText)fragmentView.findViewById(R.id.edit_other_amount);
        txt_money = (TextView)fragmentView.findViewById(R.id.txt_money);
        edit_email = (EditText)fragmentView.findViewById(R.id.edit_email);
        ll_xy= (LinearLayout)fragmentView.findViewById(R.id.ll_xy);
        ll_xy.setOnClickListener(this);
        chb_protocol = (CheckBox)fragmentView.findViewById(R.id.chb_protocol);
        RMTexts = new ArrayList<TextView>();
        RMTexts.add(txt_500);
        RMTexts.add(txt_200);
        RMTexts.add(txt_100);
        RMTexts.add(txt_60);
        for (int i = 0; i <RMTexts.size();i++) {
            RMTexts.get(i).setOnClickListener(new SelectOnClickListener(i));
        }
        btn_top_up.setOnClickListener(this);
        edit_other_amount.addTextChangedListener(new EditRemarkdListener());
        txt_money.setText("RM "+getUserBean().user_money);
        edit_other_amount.addTextChangedListener(new EditChangedListener(edit_other_amount));
        chb_protocol.setChecked(true);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_top_up:
                String email = edit_email.getText().toString();
                if (TextUtils.isEmpty(edit_other_amount.getText().toString())&& TextUtils.isEmpty(amount)) {
                    U.Toast(getActivity(), getResources().getString(R.string.czjebnwk));
                }else if (!chb_protocol.isChecked()) {
                    U.Toast(getActivity(), getResources().getString(R.string.qgxyhxy));
                } else if (TextUtils.isEmpty(email)) {
                    U.Toast(getActivity(), getResources().getString(R.string.my_data_hint_2));
                }
                else if (!StringUtil.checkEmail(email)) {
                    U.Toast(getActivity(),getResources().getString(R.string.my_data_hint_3));
                }
                else{
                    if (!TextUtils.isEmpty(edit_other_amount.getText().toString())) {
                        if (edit_other_amount.getText().toString().substring(0,1).equals(".")) {
                            return;
                        }
                    }
                    fxpfData();
                }
                break;
            case R.id.ll_xy:
                Intent intent = new Intent(getActivity(), ServiceActivity.class);
                intent.putExtra("xy","3");
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    /**
     * 调用FPX接口
     */
    public void fxpfData() {
        loadingDalog.show();
        //充值金额
        String amount ="";
        String email =edit_email.getText().toString();
        if (TextUtils.isEmpty(edit_other_amount.getText().toString())){
            amount = this.amount;
        } else {
            amount = edit_other_amount.getText().toString();
        }
        if (amount.indexOf(".")!=-1) {
            float aa = Float.parseFloat(amount);
            aa = DensityUtil.getScale(aa);
            amount = aa+"";
        }
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.FPXBANKPAY;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"amount"+amount,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("amount",amount);
            parmaMap.put("user_email",email);
            parmaMap.put("bank_id",bank_id);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 0);
        } catch (Exception e) {

        }
    }

    /**
     * FPX充值返回
     */
    public void fpxbankpayBackData() {
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.FPXBANKPAYBACK;
            int lang_id = 0;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"pay_id"+pay_id,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            SharedPreferences languagePre = getActivity().getSharedPreferences("language_choice", Context.MODE_PRIVATE);
            lang_id =languagePre.getInt("id", 1)+1;
            parmaMap.put("lang_id", lang_id+"");
            parmaMap.put("user_id", user_id);
            parmaMap.put("pay_id",pay_id);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 1);
        } catch (Exception e) {

        }
    }

    /**
     * FPX银行列表
     */
    public void fpxbankListData() {
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.FPXBANK_LIST;
            String user_id = getUserBean().user_id;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 2);
        } catch (Exception e) {

        }
    }

    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            if (action == 0) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
//                        U.Toast(getActivity(), getResources().getString(R.string.cg));
                            JSONObject data = json.getJSONObject("data");
                            JSONObject html = json.getJSONObject("html");
                            Intent intent = new Intent(getActivity(), CreditCardUrlActivity.class);
                            StringBuffer parmaMap = new StringBuffer();
                            parmaMap.append("fpx_msgType="+data.getString("fpx_msgType")+"&");
                            parmaMap.append("fpx_msgToken="+data.getString("fpx_msgToken")+"&");
                            parmaMap.append("fpx_sellerExId="+data.getString("fpx_sellerExId")+"&");
                            pay_id = data.getString("fpx_sellerExOrderNo");
                            parmaMap.append("fpx_sellerExOrderNo="+data.getString("fpx_sellerExOrderNo")+"&");
                            parmaMap.append("fpx_sellerTxnTime="+data.getString("fpx_sellerTxnTime")+"&");
                            parmaMap.append("fpx_sellerOrderNo="+data.getString("fpx_sellerOrderNo")+"&");
                            parmaMap.append("fpx_sellerId="+data.getString("fpx_sellerId")+"&");
                            parmaMap.append("fpx_sellerBankCode="+data.getString("fpx_sellerBankCode")+"&");
                            parmaMap.append("fpx_txnCurrency="+data.getString("fpx_txnCurrency")+"&");
                            parmaMap.append("fpx_txnAmount="+data.getString("fpx_txnAmount")+"&");
                            parmaMap.append("fpx_buyerEmail="+data.getString("fpx_buyerEmail")+"&");
                            parmaMap.append("fpx_checkSum="+data.getString("fpx_checkSum")+"&");
                            parmaMap.append("fpx_buyerName="+data.getString("fpx_buyerName")+"&");
                            parmaMap.append("fpx_buyerBankId="+data.getString("fpx_buyerBankId")+"&");

                            parmaMap.append("fpx_buyerBankBranch="+data.getString("fpx_buyerBankBranch")+"&");
                            parmaMap.append("fpx_buyerAccNo="+data.getString("fpx_buyerAccNo")+"&");
                            parmaMap.append("fpx_buyerId="+data.getString("fpx_buyerId")+"&");
                            parmaMap.append("fpx_makerName="+data.getString("fpx_makerName")+"&");
                            parmaMap.append("fpx_buyerIban="+data.getString("fpx_buyerIban")+"&");
                            parmaMap.append("fpx_productDesc="+data.getString("fpx_productDesc")+"&");
                            parmaMap.append("fpx_version="+data.getString("fpx_version"));

                            intent.putExtra("html",parmaMap.toString());
                            intent.putExtra("url",html.getString("url"));
                            startActivityForResult(intent,0);
                        } else if (state == 1) {
                            U.Toast(getActivity(), getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(getActivity(), getResources().getString(R.string.wdl));
                        } else if (state == 3) {
                            U.Toast(getActivity(), getResources().getString(R.string.cscw));
                        }
                    } catch (Exception e) {
                    }
                }
                loadingDalog.dismiss();
            }
            if (action == 1) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
//                            U.Toast(getActivity(), getResources().getString(R.string.cg));
                            U.Toast(getActivity(),json.getString("pay_meg"));
                        }else if (state == 1) {
                            U.Toast(getActivity(), getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(getActivity(), getResources().getString(R.string.cscw));
                        } else if (state == 3) {
                            U.Toast(getActivity(), getResources().getString(R.string.wdl));
                        }
                    } catch (Exception e) {
                    }
                }
            }
            else if (action == 2) {
                if (null != result && result instanceof JSONObject) {
                    try {
                        JSONObject json = (JSONObject) result;
                        int state = (int) json.getInt("State");
                        if (state == 0) {
                            JSONArray bank = json.getJSONArray("fpxbanklist");
                            listBanks = Logic.getListToBean(bank, new FPXBean());
                            showBank();
                        } else if (state == 1) {
                            U.Toast(getActivity(), getResources().getString(R.string.qmsb));
                        } else if (state == 2) {
                            U.Toast(getActivity(), getResources().getString(R.string.cscw));
                        }
                    } catch (Exception e) {
                    }
                }
            }
        }
    };

    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }

    public class SelectOnClickListener implements View.OnClickListener{
        int pos;
        public SelectOnClickListener(int pos) {
            this.pos = pos;
        }
        @Override
        public void onClick(View v) {
            for (int i = 0; i < RMTexts.size(); i++){
                RMTexts.get(i).setTextColor(ContextCompat.getColor(getActivity(), R.color.my_333));
                RMTexts.get(i).setBackgroundResource(R.drawable.shape_button_gray);
            }
            RMTexts.get(pos).setTextColor(ContextCompat.getColor(getActivity(), R.color.wathet3));
            RMTexts.get(pos).setBackgroundResource(R.drawable.shape_button_blue);
            edit_other_amount.setText("");
            String rm = RMTexts.get(pos).getText().toString();
            amount = rm.substring(2,rm.length());
        }
    }

    class EditRemarkdListener implements TextWatcher {

        public EditRemarkdListener() {

        }
        public EditRemarkdListener(EditText edit_count) {
        }
        private CharSequence temp;//监听前的文本
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (edit_other_amount.length() > 0) {
                for (int i = 0; i < RMTexts.size(); i++){
                    RMTexts.get(i).setTextColor(ContextCompat.getColor(getActivity(), R.color.my_333));
                    RMTexts.get(i).setBackgroundResource(R.drawable.shape_button_gray);
                }
                amount = "";
            }
        }
    };

    public void showBank(){
        getPriovince();
        ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(getActivity(),
                R.layout.simple_list_item,
                listBankId);
        spr_bank.setAdapter(adapter1);
        spr_bank.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                 FPXBean bean = listBanks.get(arg2);
                bank_id = bean.bank_id;

            }
            public void onNothingSelected(AdapterView<?> arg0) {
                arg0.setVisibility(View.VISIBLE);
            }
        });
    }


    //  通过遍历集合获得银行的名字 --备用赋值给Spinner1
    private void getPriovince(){
        listBankId=new ArrayList<String>();
        for (FPXBean bean : listBanks) {
            String cityname = bean.bank_name;
            listBankId.add(cityname);
        }
    }

    // 回调方法，从第二个页面回来的时候会执行这个方法
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (resultCode) {
            case 0:
                if (data == null) {
                    return;
                }
                if (data.hasExtra("pay_id")) {
                    fpxbankpayBackData();
                }
                break;
            default:
                break;
        }
    }

    public void money(String user_money) {
        if (null != txt_money) {
            txt_money.setText("RM "+user_money);
        }
    }

}